﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using ActiveUp.Net.Mail;
using System.IO;
using OpenPop.Pop3;
using OpenPop.Mime;

namespace Framework.WebmasterTool.Contacts
{
    public partial class Default : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public string GridViewSortExpression
        {
            get { return ViewState["GridViewSortExpression"] == null ? "AddedDate" : ViewState["GridViewSortExpression"] as string; }
            set { ViewState["GridViewSortExpression"] = value; }
        }
        public SortDirection GridViewSortOrder
        {
            get { return ViewState["GridViewSortOrder"] == null ? SortDirection.Descending : (SortDirection)ViewState["GridViewSortOrder"]; }
            set { ViewState["GridViewSortOrder"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //txtDateSearch.Attributes.Add("readonly", "readonly");
            if (!IsPostBack)
            {
                CheckPermission();
                LoadContacts();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Contact.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadContacts()
        {
            var contacts = entity.udv_Contact.Select(ct => new { ct.ContactID, ct.ViewStatus, ct.Title, ct.AddedDate, ct.ReplyStatus }).ToList();
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                contacts = contacts.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                contacts = contacts.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvContact.DataSource = contacts;
            grvContact.DataBind();
        }

        protected void grvContact_Sorting(object sender, GridViewSortEventArgs e)
        {
            //Check if the same column is sorted to switch Sort Order  
            if (GridViewSortExpression.Equals(e.SortExpression))
                GridViewSortOrder = GridViewSortOrder.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            else
                GridViewSortOrder = SortDirection.Ascending;
            //save Sort Expression and Sort Order
            GridViewSortExpression = e.SortExpression;
            if (grvContact.ToolTip == "all")
                LoadContacts();
            else
            {
                SearchContacts();
            }
        }

        protected void grvContact_DataBinding(object sender, EventArgs e)
        {
            string srcImageASC = Globals.ApplicationPath + "WebmasterTool/Images/ASC.gif";
            string srcImageDESC = Globals.ApplicationPath + "WebmasterTool/Images/DESC.gif";
            foreach (DataControlField column in grvContact.Columns)
            {
                //Remove Previous Sort Image  
                column.HeaderText = Regex.Replace(column.HeaderText, "<[^>]*>", "", RegexOptions.IgnoreCase);
                if (column.SortExpression.Equals(GridViewSortExpression))
                {
                    //set new sort image  
                    string strSortImageURL = GridViewSortOrder == SortDirection.Descending ?
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageDESC + "' />" :
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageASC + "' />";
                    column.HeaderText = String.Format("{0}{1}", column.HeaderText, strSortImageURL);
                }
            }
        }

        protected void grvContact_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvContact.PageIndex = e.NewPageIndex;
            if (grvContact.ToolTip == "all")
                LoadContacts();
            else
            {
                SearchContacts();
            }
        }

        public void SearchContacts()
        {
            var contacts = entity.udv_Contact.Select(ct => new { ct.ContactID, ct.ViewStatus, ct.Title, ct.AddedDate, ct.ReplyStatus }).ToList();
            if (txtDateSearch.Text.Trim() == "" && chkIsAnswered.Checked == true)
            {
                contacts = contacts.Where(ct => ct.ReplyStatus == false).ToList();
            }
            else if (txtDateSearch.Text.Trim() != "" && chkIsAnswered.Checked == false)
            {
                string dateSearch = txtDateSearch.Text;
                contacts = contacts.Where(ct => ct.AddedDate.Value.ToString("dd/MM/yyyy").Contains(dateSearch)).ToList();
            }
            else if (txtDateSearch.Text.Trim() != "" && chkIsAnswered.Checked == true)
            {
                string dateSearch = txtDateSearch.Text;
                contacts = contacts.Where(ct => ct.ReplyStatus == false && ct.AddedDate.Value.ToString("dd/MM/yyyy").Contains(dateSearch)).ToList();
            }
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                contacts = contacts.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                contacts = contacts.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvContact.DataSource = contacts;
            grvContact.DataBind();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grvContact.Rows)
            {
                bool isChecked = ((HtmlInputCheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    int contactID = int.Parse(((HtmlInputCheckBox)row.FindControl("chkSelect")).Attributes["title"].Trim());
                    udv_Contact contactDelete = entity.udv_Contact.Where(ct => ct.ContactID == contactID).FirstOrDefault();
                    if (contactDelete != null)
                    {
                        //create db log
                        CreateDBLog(null, null, TypeAction.Delete, "Xoá liên hệ: " + contactDelete.Title + " - " + string.Format("{0:dd/MM/yyyy HH:mm:ss}", contactDelete.AddedDate), contactDelete.Content, "", "", "",
                            "", "", "", "");

                        entity.DeleteObject(contactDelete);
                        entity.SaveChanges();
                    }
                }
            }
            if (grvContact.ToolTip == "all")
                LoadContacts();
            else
            {
                SearchContacts();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvContact.PageIndex = 0;
            grvContact.ToolTip = "search";
            SearchContacts();
        }

        public int CheckGetMailImap(ref Imap4Client imap, ref Pop3Client pop3)
        {
            int flagImap = 0;
            udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
            try
            {
                if (emailHostSetting.SSL == false)
                    imap.Connect(emailHostSetting.ServerMailIMAP, emailHostSetting.PortMailIMAP.Value);
                else
                    imap.ConnectSsl(emailHostSetting.ServerMailIMAP, emailHostSetting.PortMailIMAP.Value);
                flagImap = 1;
            }
            catch
            {
                try
                {
                    pop3.Connect(emailHostSetting.ServerMailIMAP, emailHostSetting.PortMailIMAP.Value, emailHostSetting.SSL.Value);
                    flagImap = 0;
                }
                catch
                {
                    flagImap = -1;
                }
            }
            return flagImap;
        }

        protected void btnGetMailServer_Click(object sender, EventArgs e)
        {
            udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
            Imap4Client imap = new Imap4Client();
            Pop3Client pop3 = new Pop3Client();
            int checkGetMailImap = CheckGetMailImap(ref imap, ref pop3);

            if (checkGetMailImap == -1)
            {
                string message = "Lỗi kết nối email. Sai cấu hình mail server";
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, typeof(string), "alertScript", "jAlert('" + message + "', '" + "Thông báo" + "');", true);
                return;
            }
            else if (checkGetMailImap == 1)
            {
                try
                {
                    imap.Login(emailHostSetting.MailAccount, Globals.Base64Decode(emailHostSetting.Password));
                    Mailbox inbox = imap.SelectMailbox("inbox");
                    int[] ids = inbox.Search("UNSEEN");
                    if (ids != null && ids.Length > 0)
                    {
                        for (int i = 0; i < ids.Length; ++i)
                        {
                            ActiveUp.Net.Mail.Message message = inbox.Fetch.MessageObject(ids[i]);
                            FlagCollection flags = new FlagCollection();
                            flags.Add("Seen");
                            inbox.AddFlags(ids[i], flags);
                            udv_Contact contactFromServer = new udv_Contact();
                            contactFromServer.FullName = message.From.Name;
                            contactFromServer.Address = "";
                            contactFromServer.Tel = "";
                            contactFromServer.Email = message.From.Email;
                            contactFromServer.Title = message.Subject;
                            contactFromServer.Content = message.BodyHtml.Text;
                            contactFromServer.AddedDate = message.Date;
                            contactFromServer.ViewStatus = false;
                            contactFromServer.ReplyStatus = false;
                            for (int j = 0; j < message.Attachments.Count; j++)
                            {
                                message.Attachments[i].StoreToFile(Path.Combine(Path.GetTempPath(), message.Attachments[i].Filename));
                                contactFromServer.Content += "</br> File đính kèm " + (j + 1).ToString() + ": " + "<a href='" + Path.Combine(Path.GetTempPath(), message.Attachments[i].Filename) + "' target='_blank'>" + message.Attachments[i].Filename + "</a>";
                            }
                            entity.AddToudv_Contact(contactFromServer);
                            entity.SaveChanges();
                        }
                    }
                }
                catch
                {
                    string message = "Lỗi kết nối email imap. Sai username hoặc password";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, typeof(string), "alertScript", "jAlert('" + message + "', '" + "Thông báo" + "');", true);
                    return;
                }
            }
            else if (checkGetMailImap == 0)
            {
                try
                {
                    pop3.Authenticate(emailHostSetting.MailAccount, Globals.Base64Decode(emailHostSetting.Password));
                    List<string> uids = pop3.GetMessageUids();
                    List<string> seenUids = new List<string>();
                    List<OpenPop.Mime.Message> newMessages = new List<OpenPop.Mime.Message>();
                    for (int i = 0; i < uids.Count; i++)
                    {
                        string currentUidOnServer = uids[i];
                        if (!seenUids.Contains(currentUidOnServer))
                        {
                            OpenPop.Mime.Message unseenMessage = pop3.GetMessage(i + 1);
                            //newMessages.Add(unseenMessage);

                            udv_Contact contactFromServer = new udv_Contact();
                            contactFromServer.FullName = unseenMessage.Headers.From.DisplayName;
                            contactFromServer.Address = "";
                            contactFromServer.Tel = "";
                            contactFromServer.Email = unseenMessage.Headers.From.Address;
                            contactFromServer.Title = unseenMessage.Headers.Subject;
                            contactFromServer.Content = unseenMessage.FindFirstHtmlVersion().GetBodyAsText();
                            contactFromServer.AddedDate = unseenMessage.Headers.DateSent;
                            contactFromServer.ViewStatus = false;
                            contactFromServer.ReplyStatus = false;
                            int j = 0;
                            foreach (MessagePart attachment in unseenMessage.FindAllAttachments())
                            {
                                j++;
                                FileStream Stream = new FileStream(Path.Combine(Path.GetTempPath(), attachment.FileName), FileMode.Create);
                                BinaryWriter BinaryStream = new BinaryWriter(Stream);
                                BinaryStream.Write(attachment.Body);
                                BinaryStream.Close();
                                attachment.Save(Stream);
                                contactFromServer.Content += "</br> File đính kèm " + j.ToString() + ": " + "<a href='" + Path.Combine(Path.GetTempPath(), attachment.FileName) + "' target='_blank'>" + attachment.FileName + "</a>";
                            }
                            seenUids.Add(currentUidOnServer);
                        }
                    }
                }
                catch
                {
                    string message = "Lỗi kết nối email pop3. Sai username hoặc password";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, typeof(string), "alertScript", "jAlert('" + message + "', '" + "Thông báo" + "');", true);
                    return;
                }
            }
            LoadContacts();
        }

        protected void btnOrder_Click(object sender, EventArgs e)
        {
            Response.Redirect(Globals.ApplicationPath + "WebmasterTool/Orders/Default.aspx");
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}